/**
 * 修补Project对象
 * */

const mysql = require('../utils/mysql_util');
const prodMysql = require('../utils/prod_mysql_util');
// const mongod = require('../utils/mongod_util');
// const prodMongod = require('../utils/prod_mongod_util');
const projectJson = require('../mongod/project_json');
const prodProjectJson = require('../mongod/prod_project_json');
const eachLimit = require('async/eachLimit');
const _ = require('lodash');

/**
 * 仅仅保存方案Json 数据（json字符串），保存到mongodb
 * @param strDesignJson
 * @param designId
 * @param userId
 */
const saveDesignJson = (mongo_key, strDesignJson, designId, userId) =>
  new Promise((res, rej) => {
    const designjson = new projectJson();
    designjson._id = mongo_key;
    designjson.projectData = strDesignJson;
    designjson.projectDesignId = designId;
    // designjson.userId = userId;
        // 将方案json数据保存到mongodb，
    designjson.save((err) => {
      if (err) {
        console.log(`保存${designId}方案Json数据失败！`);
        rej(err);
      } else {
        console.log(`保存${designId}方案Json数据成功！`);
        res();
      }
    });
  });
/**
 * 通过方案或户型编码，获取最新json数据
 * @param designId
 */
const getProjectJson = designId => new Promise((res, rej) => {
  // const dataMap = {};
  const projectVersionSql = `select mongo_key from project_version where designId='${designId}' and ` +
    `version= (select max(version) from project_version where designId='${designId}')`;
  prodMysql.execute(projectVersionSql)
    .then((projectVersion) => {
      if (projectVersion && projectVersion[0]) {
        prodProjectJson.find({ _id: projectVersion[0].mongo_key }, (err, projectJsonData) => {
          if (err) {
            console.log(`读取${designId}方案Json数据失败！`);
            rej(err);
          } else if (projectJsonData && projectJsonData[0]) {
            console.log(`读取${designId}方案Json数据成功！`);
            res(projectJsonData[0]);
          } else {
            res();
          }
        });
      } else {
        res();
      }
    })
    .catch((err) => {
      if (err) rej(err);
    });
});

/**
 * 判断当前方案最新版本是否存在json数据，如果存在则返回null，不存在则返回最新版本编码
 */
const getMongoKeyAndjudgeProjectHaveJson = designId => new Promise((res, rej) => {
        // 判断该户型是否存在最新json数据
  const projectVersionSql = `select mongo_key from project_version where designId='${designId}' and ` +
          `version= (select max(version) from project_version where designId='${designId}')`;
  mysql.execute(projectVersionSql).then((projectVersion) => {
    if (projectVersion && projectVersion[0]) {
      projectJson.find({ _id: projectVersion[0].mongo_key }, (err, projectJsonData) => {
        if (err) {
          console.log(`读取${designId}方案Json数据失败！`);
          rej(err);
        } else if (projectJsonData && projectJsonData[0]) {
          mysql.execute(`insert into del_designId_version (designId) values('${designId}')`).then(() => {
            console.log(`方案${designId}存在最新版本json数据！`);
            res(null);
          }).catch((err1) => {
            rej(err1);
          }
          );
        } else {
          res(projectVersion[0].mongo_key);
        }
      });
    } else {
      res();
    }
  }).catch((err) => {
    if (err) rej(err);
  });
});


/**
 * 补充户型json数据
 * 查询测试环境户型数据，如果不存在对应的json数据
 * 则从外网取出对应的json补充到测试环境
 */
exports.addProjectJson = () => {
  const sqlQueryDesignId = 'select designId from project where asset_type=4  and designId not in(select designId from del_designId)';
  // 取出所有的户型id
  mysql.execute(sqlQueryDesignId).then((results) => {
    // 异步，一次执行10个
    eachLimit(results, 10, (result, callback) => {
      // 判断该户型是否存在最新json数据
      const designId = result.designId;
      getMongoKeyAndjudgeProjectHaveJson(designId).then((mongoKey) => {
        if (mongoKey) {
          // 最新版本不存在json数据，需要从生产环境获取json数据，补充。
          getProjectJson(designId).then((jsonData) => {
            // 保存Json数据
            const projectData = jsonData._doc.projectData;
            const userId = jsonData.userId;
            saveDesignJson(mongoKey, projectData, designId, userId).then(() => {
              setImmediate(callback);
            }).catch((err) => {
              setImmediate(callback);
            });
          }).catch((err) => {
            setImmediate(callback);
          });
        } else {
          setImmediate(callback);
        }
      }).catch((err) => {
        setImmediate(callback);
      });
    });
  }).catch((err) => {
    throw err;
  });
};

